package com.zang.blogz.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zang.blogz.constant.ResultConstant;
import com.zang.blogz.entity.Photo;
import com.zang.blogz.mapper.PhotoMapper;
import com.zang.blogz.result.Result;
import com.zang.blogz.service.PhotoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 照片 服务实现类
 * </p>
 *
 * @author 朵橙i
 * @since 2022-06-17
 */
@Service
public class PhotoServiceImpl extends ServiceImpl<PhotoMapper, Photo> implements PhotoService {

    @Override
    public List<Photo> photoList(Integer albumId) {

        LambdaQueryWrapper<Photo> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Photo::getAlbumId, albumId);

        return list(queryWrapper);
    }

    @Override
    public Boolean photoAlbumIsNull(Integer albumId) {

        LambdaQueryWrapper<Photo> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Photo::getAlbumId, albumId);

        return count(queryWrapper) > 0 ;
    }

    @Override
    public Result<Photo> savePhoto(Photo photo) {

        if (photo.getAlbumId() == null){

            throw new RuntimeException("您当前还没有选择相册哦");
        }

        if (StringUtils.isBlank(photo.getPhotoName())){

            photo.setPhotoName(RandomUtil.randomNumbers(6));
        }

        save(photo);

        return Result.ok(ResultConstant.SAVE_SUCCESS,photo) ;
    }

    @Override
    public Result<String> deletePhoto(Integer photoId) {

        if (removeById(photoId)){

            return Result.ok(ResultConstant.DELETE_SUCCESS);
        }

        return Result.error(ResultConstant.DELETE_FAIL);
    }

    @Override
    public Result<String> movePhotos(String ids, Integer albumId) {

        Set<Integer> collect = Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toSet());

        LambdaUpdateWrapper<Photo> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.in(Photo::getId, collect );
        updateWrapper.set(Photo::getAlbumId, albumId);

        update(updateWrapper);

        return Result.ok(ResultConstant.UPDATE_SUCCESS);

    }
}
